package service

import (
	"log"
	"net/http"
	"strconv"
	"user/pojo"

	"github.com/gin-gonic/gin"
)

var userList = []pojo.User{}

func FindAllUsers(c *gin.Context) {
	// c.JSON(http.StatusOK, userList)

	users := pojo.FindAllUsers()

	c.JSON(http.StatusOK, users)

}

func FindByUserId(c *gin.Context) {
	user := pojo.FindByUserId(c.Param("id"))

	if user.Id == 0 {
		c.JSON(http.StatusNotFound, "Error1")
		return
	}

	log.Println("User ->", user)
	c.JSON(http.StatusOK, user)
}

func PostUser(c *gin.Context) {
	user := pojo.User{}
	err := c.BindJSON(&user)
	if err != nil {
		c.JSON(http.StatusNotAcceptable, "ERROR: "+err.Error())
		return
	}

	userList = append(userList, user)

	c.JSON(http.StatusOK, "successfully posted")
}

func DeleteUser(c *gin.Context) {
	userId, _ := strconv.Atoi(c.Param("id"))
	for _, user := range userList {
		log.Println(user)
		if user.Id == userId {
			userList = append(userList[:userId], userList[userId+1:]...)
			c.JSON(http.StatusOK, "suucess delete!!")
			return
		}
	}

	c.JSON(http.StatusNotFound, "err  delete")
}

func PutUser(c *gin.Context) {
	beforeUser := pojo.User{}
	err := c.BindJSON(&beforeUser)
	if err != nil {
		c.JSON(http.StatusBadRequest, "ERROR1")
	}

	userId, _ := strconv.Atoi(c.Param("id"))
	for key, user := range userList {
		if user.Id == userId {
			userList[key] = beforeUser
			log.Println(userList[key])
			c.JSON(http.StatusOK, "suucess Put!!")
			return
		}
	}

	c.JSON(http.StatusNotFound, "err  Put")
}
